package com.taptech.doufu.ui.fragment

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONObject
import com.taptech.doufu.R
import com.taptech.doufu.constant.Constant
import com.taptech.doufu.services.personalcenter.AccountService
import com.taptech.doufu.ui.activity.*
import com.taptech.doufu.ui.activity.me.MyCoinActivity
import com.taptech.doufu.ui.activity.weex.SimpleWeexActivity
import com.taptech.doufu.util.GlideUtil
import com.taptech.doufu.util.GsonUtil
import com.taptech.doufu.util.sp.DiaoBaoSharedPreferences
import com.taptech.doufu.weex.http.TFHttpUtil
import kotlinx.android.synthetic.main.fragment_me.*

class MeFragment :DiaobaoBaseFragment() {

    var isSign = false
    var isLogin = false
    var urlBean = UrlBean()
    var userBean = UserBean()
    var descBean = DescBean()

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val view = inflater.inflate(R.layout.fragment_me,null)
        return view
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView()
        refreshData()
    }

    private fun initView() {
        layHead.setOnClickListener {
            if (!AccountService.getInstance().isLogin) {
                AccountService.getInstance().jumpToLogin()
                return@setOnClickListener
            }
            context?.let { it1 -> UserDetailActivity.startActivity(it1, AccountService.getInstance().userUid) }

        }
        ivLogin.setOnClickListener {
            AccountService.getInstance().jumpToLogin()
        }
        ivSign.setOnClickListener {
            if (!AccountService.getInstance().isLogin) {
                AccountService.getInstance().jumpToLogin()
                return@setOnClickListener
            }
            BrowseActivity.startActivity(context,urlBean.sign)
        }
        layLevel.setOnClickListener {
            if (!AccountService.getInstance().isLogin) {
                AccountService.getInstance().jumpToLogin()
                return@setOnClickListener
            }
            BrowseActivity.startActivity(context,"https://api.doufu.la/level")
        }
        layActivity.setOnClickListener {
            if (!AccountService.getInstance().isLogin) {
                AccountService.getInstance().jumpToLogin()
                return@setOnClickListener
            }

            val intent = Intent(context, PersonalNewDynamicActivity::class.java)
            intent.putExtra(Constant.UID, AccountService.getInstance().userUid)
            context?.startActivity(intent)
        }
        layAttention.setOnClickListener {
            if (!AccountService.getInstance().isLogin) {
                AccountService.getInstance().jumpToLogin()
                return@setOnClickListener
            }
            val intent = Intent(context, PersonalAttentionsActivity::class.java)
            intent.putExtra(Constant.UID, AccountService.getInstance().userUid)
            context?.startActivity(intent)
        }
        layFans.setOnClickListener {
            if (!AccountService.getInstance().isLogin) {
                AccountService.getInstance().jumpToLogin()
                return@setOnClickListener
            }
            val intent = Intent(context, PersonalFansActivity::class.java)
            intent.putExtra(Constant.UID, AccountService.getInstance().userUid)
            context?.startActivity(intent)
        }
        layPublish.setOnClickListener {
            if (!AccountService.getInstance().isLogin) {
                AccountService.getInstance().jumpToLogin()
                return@setOnClickListener
            }
            MyWorksActivity.startActivity(context)
//            SimpleWeexActivity.startActivity(context,"vue/personalcenter/TFPublishWorks.js?needLogin=1")
        }
        layAuthorHelp.setOnClickListener {
            if (!AccountService.getInstance().isLogin) {
                AccountService.getInstance().jumpToLogin()
                return@setOnClickListener
            }
            BrowseActivity.startActivity(context,"http://api.doufu.la/index.php/journal/detail?id=400")
        }
        layIncome.setOnClickListener {
            if (!AccountService.getInstance().isLogin) {
                AccountService.getInstance().jumpToLogin()
                return@setOnClickListener
            }
            BrowseActivity.startActivity(context,urlBean.my_income)
        }
        layAssets.setOnClickListener {
            if (!AccountService.getInstance().isLogin) {
                AccountService.getInstance().jumpToLogin()
                return@setOnClickListener
            }
            SimpleWeexActivity.startActivity(context,"vue/personalcenter/MyTreasures/MyTreasure.js?needLogin=1")
        }
        layCoin.setOnClickListener {
            if (!AccountService.getInstance().isLogin) {
                AccountService.getInstance().jumpToLogin()
                return@setOnClickListener
            }
            MyCoinActivity.startActivity(context)
        }
        layVip.setOnClickListener {
            if (!AccountService.getInstance().isLogin) {
                AccountService.getInstance().jumpToLogin()
                return@setOnClickListener
            }
            SimpleWeexActivity.startActivity(context,"vue/newVip/vipCenter.js?needLogin=1")
        }
        layInviteFriend.setOnClickListener {
            if (!AccountService.getInstance().isLogin) {
                AccountService.getInstance().jumpToLogin()
                return@setOnClickListener
            }
            SimpleWeexActivity.startActivity(context,"vue/personalcenter/voucher/TFShareToGetVoucher.js")
        }
        layMedal.setOnClickListener {
            if (!AccountService.getInstance().isLogin) {
                AccountService.getInstance().jumpToLogin()
                return@setOnClickListener
            }
            BrowseActivity.startActivity(context,urlBean.my_medal)
        }
        layRule.setOnClickListener {
            if (!AccountService.getInstance().isLogin) {
                AccountService.getInstance().jumpToLogin()
                return@setOnClickListener
            }
            BrowseActivity.startActivity(context,"https://api.doufu.la/journal/detail?id=686")
        }
        layFeedback.setOnClickListener {
            if (!AccountService.getInstance().isLogin) {
                AccountService.getInstance().jumpToLogin()
                return@setOnClickListener
            }
            BrowseActivity.startActivity(context,"https://api.doufu.la/index.php/help/question")
        }
        laySetting.setOnClickListener {
            if (!AccountService.getInstance().isLogin) {
                AccountService.getInstance().jumpToLogin()
                return@setOnClickListener
            }
            val setIntent = Intent(context, MoreSetActivity::class.java)
            context?.startActivity(setIntent)
        }

    }

    private fun refreshData() {
        isLogin = AccountService.getInstance().isLogin
        updateLoginUI()
        getSignState()
        getData()
    }

    fun getData() {
        val url = "http://api.doufu.la/new_user/new_user/personal_center"
        TFHttpUtil.requestGet(url,null){json, error ->
            try {
                DiaoBaoSharedPreferences.setSharedPreferencesValueToString("person_info",json.toJSONString(),context)
                setData(json)
            } catch (e: Exception) {
                try {
                    val cacheJson = DiaoBaoSharedPreferences.getSharedPreferencesValueToString("person_info", context, "")
                    setData(JSON.parseObject(cacheJson))
                } catch (e: Exception) {
                    e.printStackTrace()
                }
                e.printStackTrace()
            }
            updateUi()
        }
    }

    fun setData(json: JSONObject) {
        val data = json.getJSONObject("data")
        urlBean = GsonUtil.parseJsonWithGson(data.getJSONObject("urls").toJSONString(),UrlBean::class.java)
        userBean = GsonUtil.parseJsonWithGson(data.getJSONObject("user").toJSONString(),UserBean::class.java)
        descBean = GsonUtil.parseJsonWithGson(data.getJSONObject("tints").toJSONString(),DescBean::class.java)
    }

    private fun getSignState() {
        val url = "member/signature"
        TFHttpUtil.requestGet(url,null){ json, error ->
            try {
                val data = json.getJSONObject("data")
                isSign = data.getBoolean("signatured")
            } catch (e: Exception) {
                e.printStackTrace()
            }
            updateSignUi()
        }
    }


    private fun updateLoginUI() {
        if (isLogin) {
            ivLogin.visibility = View.GONE
            ivSign.visibility = View.VISIBLE
        }else{
            ivLogin.visibility = View.VISIBLE
            ivSign.visibility = View.GONE
        }
    }

    private fun updateSignUi() {
        if (isSign) {
            ivSign.setImageResource(R.drawable.icon_personal_signed)
        }else{
            ivSign.setImageResource(R.drawable.icon_personal_sign)
        }
    }

    private fun updateUi() {
        if (isLogin) {
            GlideUtil.displayCircleImage(ivHead,userBean.icon)
            tvUserName.text = userBean.nickname
            layLevel.visibility = View.VISIBLE
            GlideUtil.displayImage(ivLevel,userBean.level_icon)
            tvLevel.text = "豆花 Lv.${userBean.level}"
            tvActivity.text = userBean.activity_count
            tvAttention.text = userBean.attentions_counts
            tvFans.text = userBean.fans_counts
        }else{
            layLevel.visibility = View.GONE
            tvActivity.text = "0"
            tvAttention.text ="0"
            tvFans.text = "0"
        }
        if (descBean.publish_production.isNotEmpty()) {
            tvPublishDesc.text = descBean.publish_production
        }
        if (descBean.my_income.isNotEmpty()) {
            tvIncomeDesc.text = descBean.my_income
        }
        if (descBean.my_coins.isNotEmpty()) {
            tvCoinDesc.text = descBean.my_coins
        }
        if (descBean.my_assets.isNotEmpty()) {
            tvAssetsDesc.text = descBean.my_assets
        }
        if (descBean.my_membership.isNotEmpty()) {
            tvVipDesc.text = descBean.my_membership
        }
        if (descBean.my_medal.isNotEmpty()) {
            tvMedalDesc.text = descBean.my_medal
        }
        if (descBean.setting.isNotEmpty()) {
            tvSettingDesc.text = descBean.setting
        }
    }


    data class UserBean(
            val uid:String = "",
            val nickname:String = "",
            val attentions_counts:String = "0",
            val fans_counts:String = "0",
            val icon:String = "",
            val activity_count:String = "",
            val coin_count:String = "",
            val level:Int = 0,
            val level_icon:String = ""
    )

    data class DescBean(
            val publish_production:String = "",
            val my_coins:String = "",
            val my_income:String = "",
            val my_assets:String = "",
            val my_membership:String = "",
            val publish_bbs:String = "",
            val my_medal:String = "",
            val my_beans:String = "",
            val setting:String = ""
    )

    data class UrlBean(
            val sign:String = "https://api.doufu.la/signature",
            val my_coin:String = "https://api.doufu.la/reward/recharge",
            val my_income:String = "https://api.doufu.la/reward/gift",
            val my_ticket:String = "https://api.doufu.la/reward/gift/goMonthlyTicket",
            val my_vip:String = "https://api.doufu.la/memberCenter/index",
            val my_medal:String = "https://api.doufu.la/myMedal/index"
    )
}